package com.matt.controller.api.web;

import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.domain.Clientele;
import com.matt.foundation.constant.CommonConstant;
import com.matt.commons.exception.BusinessException;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.foundation.dto.teach.ChildDTO;
import com.matt.foundation.dto.teach.ClassDTO;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.StatusResponse;
import com.matt.foundation.query.ClienteleQuery;
import com.matt.foundation.query.PageableQuery;
import com.matt.foundation.vo.*;
import com.matt.service.ClienteleService;
import com.matt.service.ContractService;
import com.matt.remoteCall.SsoCallService;
import com.matt.service.TeachCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * ********************
 * description :客户控制器
 * Created by Ron
 * from com.matt
 * on 2018/6/14 0014.
 * *********************
 */
@RestController
@RequestMapping("/web/clientele/")
@Api(tags = "CRM - 客户")
public class ClienteleController {

    @Autowired
    private ClienteleService clienteleService;

    @Autowired
    private ContractService contractService;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private TeachCallService teachCallService;

    @RequestMapping(value = "/get")
    public StatusResponse get() {
        AreaDTO areaDTO = ssoCallService.getAreaDTO("c4f2d31bd27dc744fdf2d846f283c8be-a4c8daf5e4cc4eddb6e5b2393b2db110-1660979598497");
        return StatusResponse.success(areaDTO);
    }

    /**
     * 根据用户名模糊查询
     *
     * @param name
     * @param classId
     * @return
     */
    @RequestMapping(value = "/find")
    @ApiOperation(value = "根据用户名，客户名，宝宝名，模糊查询 以及 班级id 查询客户名和id")
    public StatusResponse findClientele(@RequestHeader String ticket, String name, String classId, PageableQuery query) {
        String areaId = ssoCallService.getStaffDTO(ticket).getAreaId();


        List<String> ids = null;
        List<ChildDTO> children = null;
        if (StringUtils.isNotBlank(classId)) {
            //有班级id的时候，限定客户id范围
            children = teachCallService.getChildClassList(ticket, 1, null, classId, null);
            if (children != null && children.size() > 0) {
                ids = children.stream().map(o -> o.getCrmClienteleId()).collect(Collectors.toList());
            }
            if (ids == null) {
                ids = new ArrayList<>();
            }
        }

        PageRequest pageRequest = PageRequest.of(query.getPageNum(), query.getPageSize());

        Page<ClienteleListVO> result = clienteleService.findByName(areaId, name, ids, pageRequest);
        if (result == null) {
            return StatusResponse.success();
        }

        if (children == null) {
            //重新获取班级关系
            ids = result.getContent().stream().map(o -> o.getId()).collect(Collectors.toList());
            children = teachCallService.getChildClassList(ticket, 1, null, null, ids);
        }

        //重新装配班级信息
        if (children != null && children.size() > 0) {
            List<ChildDTO> finalChildren = children;
            result.getContent().stream().forEach(o -> {
                Optional<ChildDTO> op = finalChildren.stream().filter(c -> o.getId().equals(c.getCrmClienteleId())).findFirst();
                if (op.isPresent()) {
                    ChildDTO child = op.get();
                    o.setClassNames(child.getClassNames());
                }
            });
        }

        return StatusResponse.success(result);
    }

//    /**
//     * 根据用户名模糊查询
//     *
//     * @param name
//     * @return
//     */
//    @RequestMapping(value = "/find_clientele_name")
//    @ApiOperation(value = "根据用户名模糊查询客户名和id", httpMethod = "GET", response = ClienteleNameVo.class)
//    public StatusResponse findByName(@RequestHeader String ticket, String name) {
//        String areaId = ssoCallService.getStaffDTO(ticket).getAreaId();
//        return StatusResponse.success(clienteleService.findByName(areaId, name, null));
//    }

    /**
     * 查询客户  by 孩子姓名
     *
     * @param childName 孩子姓名(不可变)
     * @return
     */
    @RequestMapping(value = "/find_childs_childName")
    @ApiOperation(value = "根据宝宝姓名查询客户", httpMethod = "GET", response = Clientele.class)
    public StatusResponse findByChildren(@RequestHeader String ticket, String childName) {
        String areaId = ssoCallService.getStaffDTO(ticket).getAreaId();
        return StatusResponse.success(clienteleService.findByChildName(areaId, childName));
    }

    /**
     * 线索转为客户
     *
     * @param ticket
     * @param clienteleSaveVo
     * @param productRecords  产品记录
     * @return
     */
    @RequestMapping(value = "/change_clientele")
    @ApiOperation(value = "线索转为客户", httpMethod = "POST", response = ClienteleDetailVo.class)
    public StatusResponse changeClientele(@RequestHeader String ticket, ClienteleSaveVo clienteleSaveVo, String productRecords) {

        String areaId = ssoCallService.getStaffDTO(ticket).getAreaId();
        if (Objects.isNull(clienteleSaveVo.getBirthday())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "生日不能为空");
        }
        if (StringUtils.isEmpty(clienteleSaveVo.getSysChildName())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "参数错误");
        }

        //校验重名孩子是否存在，存在则不能新增
        Clientele clientele = clienteleService.findBySystemChildName(areaId, clienteleSaveVo.getSysChildName(), clienteleSaveVo.getMobile());
//        Clientele clientele= clienteleService.findBySystemChildNameAndId(ticket,clienteleSaveVo.getClienteleId(),clienteleSaveVo.getSysChildName());
        if (clientele != null)
            return StatusResponse.error(ErrorCode.CLIENTELE_EXIST, "该园区此姓名的孩子已经存在，请更改孩子姓名！");

        return StatusResponse.success(clienteleService.save(ticket, clienteleSaveVo, productRecords, areaId));
    }

    /**
     * 客户修改
     *
     * @param clientele
     * @param productRecords 产品记录
     * @param channelId
     * @return
     */
    @RequestMapping(value = "/update")
    @ApiOperation(value = "编辑客户", httpMethod = "POST", response = ClienteleDetailVo.class)
    public StatusResponse update(@RequestHeader(CommonConstant.TICKET) String ticket, Clientele clientele, String productRecords, String channelId) {
        //校验重名孩子是否存在，存在则不能新增
        if (StringUtils.isEmpty(clientele.getChildName())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "参数错误");
        }

        Clientele vo = clienteleService.findBySystemChildNameAndId(clientele.getAreaId(), clientele.getId(), clientele.getSysChildName());
        if (vo != null)
            return StatusResponse.error(ErrorCode.CLIENTELE_EXIST, "该园区此姓名的孩子已经存在，请更改孩子姓名！");
        return StatusResponse.success(clienteleService.update(ticket, clientele, productRecords, channelId));
    }

    /**
     * 删除客户
     *
     * @param clienteleId
     * @return
     */
    @RequestMapping(value = "/delete")
    @ApiOperation(value = "删除客户", httpMethod = "POST", response = Clientele.class)
    public StatusResponse deleteById(@RequestHeader String ticket, String clienteleId) {
        //校验是否存在合同，如有则不能删除
        Boolean flag = contractService.findByClienteleId(clienteleId);
        if (flag == true)
            return StatusResponse.error(ErrorCode.Clientele_CONTRACT_EXIT, "客户已经签订合同，不能删除");
        return StatusResponse.success(clienteleService.deleteById(ticket, clienteleId));
    }


    /**
     * 2.我的/待补款记录    continueFillMoneyKey="cfm"
     * 备注：我的>>> stuffId is not null
     *
     * @param clienteleQuery
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/page")
    @ApiOperation(value = "分页查询客户列表", httpMethod = "GET", response = Clientele.class)
    public StatusResponse continueClientelesOrFillMoney(@RequestHeader String ticket, ClienteleQuery clienteleQuery, Pageable pageable) {
        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        clienteleQuery.setAreaId(staff.getAreaId());
        Page<Clientele> clientelePage;
        //判断是否有管理全部班级权限
        if ( ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_FULL }) ){
            clientelePage = clienteleService.continueClientelesOrFillMoney(clienteleQuery, pageable);
        }else if (ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_SALES })){
            clienteleQuery.setStaffId(staff.getId());
            clientelePage = clienteleService.continueClientelesOrFillMoney(clienteleQuery, pageable);
        }else {
            clientelePage = new PageImpl<>(new ArrayList<>(), pageable, 0);
        }

        //重新装配班级关系
        List<String> ids = clientelePage.getContent().stream().map(o -> o.getId()).collect(Collectors.toList());

        List<ChildDTO> children = teachCallService.getChildClassList(ticket, 1, null, null, ids);
        if (children != null && children.size() > 0) {
            List<ChildDTO> finalChildren = children;
            clientelePage.getContent().stream().forEach(o -> {
                Optional<ChildDTO> op = finalChildren.stream().filter(c -> o.getId().equals(c.getId())).findFirst();
                if (op.isPresent()) {
                    ChildDTO child = op.get();
                    o.setClassNames(child.getClassNames());
                }
            });
        }

        return StatusResponse.success(clientelePage);
    }

    /**
     * 1.我的/待续约客户    continueKey="ck"
     *
     * @param clienteleQuery
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/continue_clientele_page")
    @ApiOperation(value = "我的/待续约客户", httpMethod = "GET", response = ClienteleVo.class)
    public StatusResponse continueClientele(ClienteleQuery clienteleQuery, Pageable pageable) {
        return StatusResponse.success(clienteleService.continueClienteles(clienteleQuery, pageable));
    }


    /**
     * 客户详情
     *
     * @param clientelesId 客户d
     * @return
     */
    @RequestMapping(value = "/detail")
    @ApiOperation(value = "客户详情", httpMethod = "GET", response = Clientele.class)
    public StatusResponse detail(String clientelesId) {
        return StatusResponse.success(clienteleService.findById(clientelesId));
    }

    /**
     * 查询客户信息  by childName
     *
     * @param areaId
     * @param childName
     * @return
     */
    @RequestMapping(value = "/find_childs")
    @ApiOperation(value = "根据宝宝名字查询客户信息", httpMethod = "GET", response = AdviceNameVo.class)
    public StatusResponse findChilds(String areaId, String childName) {
        return StatusResponse.success(clienteleService.findChilds(areaId, childName));
    }

    /**
     * 修改客户负责人
     *
     * @param staffId     新负责人id
     * @param clienteleId 线索id
     * @return
     */
    @RequestMapping(value = "/update_clientele_staff")
    @ApiOperation(value = "移交客户", httpMethod = "POST", response = Clientele.class)
    public StatusResponse updateClienteStaff(@RequestHeader String ticket, String staffId, String staffName, String clienteleId) {
        return StatusResponse.success(clienteleService.updateClienteStaff(ticket, staffId, staffName, clienteleId));
    }

    @RequestMapping(value = "/childrenIdDetail")
    @ApiOperation(value = "学生ID查：客户详情", httpMethod = "POST", response = Clientele.class)
    public StatusResponse childrenIdDetail(String childrenId) {
        ChildDTO childDTO =  teachCallService.childrenIdByChildren(childrenId);
        return StatusResponse.success(clienteleService.findById(childDTO.getCrmClienteleId()));
    }
}
